import React, { useState, useRef } from 'react';
import { useRequest } from 'ahooks'; // 或您使用的请求库

const AsyncRequestProcessor = () => {
  const taskQueue = useRef([]);
  const resultMap = useRef(new Map());
  const [orderedResults, setOrderedResults] = useState([]);

  // 使用 useRequest 处理异步请求
  const { run: sendRequest } = useRequest(
    async (buttonId) => {
      // 模拟异步请求 settimeout 模拟延迟
      await new Promise((resolve) => setTimeout(resolve, Math.random() * 1000));
      return `点击${buttonId}`;
    },

    {
      manual: true,
      onSuccess: (data, [buttonId, taskId]) => {
        // 请求成功时调用processResponse处理数据返回结果
        processResponse(taskId, data);
      },
    }
  );

  // 点击按钮时为该次点击生成唯一的taskId，然后执行异步请求
  const handleButtonClick = (buttonId) => {
    const taskId = `${buttonId}_${Date.now()}`;
    taskQueue.current = [...taskQueue.current, { id: taskId, buttonId }];
    sendRequest(buttonId, taskId); // 触发请求
  };

  // 处理数据返回结果，按顺序处理
  const processResponse = (taskId, data) => {
    resultMap.current.set(taskId, data);

    const newOrderedResults = [];
    const remainingQueue = [];

    // 按顺序检查队列
    for (const task of taskQueue.current) {
      if (resultMap.current.has(task.id)) {
        newOrderedResults.push(resultMap.current.get(task.id));
      } else {
        remainingQueue.push(task);
        break; // 遇到第一个未完成的任务就停止
      }
    }

    // 更新状态
    taskQueue.current = remainingQueue;
    setOrderedResults((prev) => [...prev, ...newOrderedResults]);
  };

  return (
    <div className="async-processor">
      <button onClick={() => handleButtonClick('btn1')}>按钮1</button>
      <button onClick={() => handleButtonClick('btn2')}>按钮2</button>
      <button onClick={() => handleButtonClick('btn3')}>按钮3</button>

      <div className="results-status">
        {orderedResults.length > 0 && (
          <ul>
            {orderedResults.map((result, index) => (
              <li key={index}>{result}</li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
};

export default AsyncRequestProcessor;
